package com.yobol.jgrowth.service.impl;

import com.github.pagehelper.PageHelper;
import com.yobol.jgrowth.domain.User;
import com.yobol.jgrowth.exception.PasswordNotTrueException;
import com.yobol.jgrowth.exception.UsernameDuplicationException;
import com.yobol.jgrowth.exception.UsernameNotFoundException;
import com.yobol.jgrowth.mapper.UserMapper;
import com.yobol.jgrowth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * User Service Implement
 *
 * @author
 * @create 2018-03-25 19:30
 **/

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int addUser(User user) throws UsernameDuplicationException {
        List<User> users = userMapper.getUserByName(user.getName());
        //昵称已经被注册
        if (users == null || !users.isEmpty()){
            throw new UsernameDuplicationException();
        }

        return userMapper.insert(user);
    }

    @Override
    public User validateUser(User user) throws UsernameNotFoundException, PasswordNotTrueException {
        List<User> users = userMapper.getUserByName(user.getName());
        //用户名不存在
        if (users.isEmpty()){
            throw new UsernameNotFoundException();
        }
        User temp = users.get(0);
        //密码不匹配
        if (!temp.getPwd().equals(user.getPwd())){
            throw new PasswordNotTrueException();
        }
        return temp;
    }

    @Override
    public void loginOut(User user) {
        userMapper.updateLatestOnlineTime(user);
    }

    @Override
    public List<User> selectAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        return userMapper.selectAll();
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }
}
